<template>
  <div style="background-color: rgb(247,247,247); border: 1px solid #ccc; border-radius: 10px;overflow-y: scroll;padding: 20px;  height: 525px;  ">
    <div style="margin: 10px 0; width: 100%;">
      <div style="text-align: right">
        视频通话 自己  {{ uid }}
        <el-button  v-if="isaccept" type="success"  @click="accept">接受</el-button>
        <video ref="v1" autoplay playsinline style="width: 380px;height: 190px;"></video>
        <el-divider></el-divider>
        视频通话 好友  {{ tid }}
        <video ref="v2" autoplay playsinline style="width: 380px;height: 190px;"></video>
      </div>
    </div>
  </div>

</template>

<script setup>
import socket from "../utils/websocket.ts"
import {websocketStore} from "@/stores/websokcet"
import {useUserStore} from "@/stores/user";
import {onMounted, reactive, ref} from "vue";
import {onBeforeRouteUpdate, useRoute} from "vue-router";

let uid = ref('')
let tid = ref('')
const route = useRoute()
const isaccept = ref(false);
const userStore = useUserStore()
const user = userStore.getUser
let query = reactive({})
let fid = ref('')

onBeforeRouteUpdate((to)=>{
  fid = to.query.fid
  console.log(fid)

})

onMounted(()=>{
  console.log(route.query)
  query = route.query
  console.log(query)
  console.log(fid)
  loginWebsocket()
  getuid()
})

const getuid = ()=>{
  console.log(fid)
  query.to = route.query.fid
  fid = route.query.fid
}

const loginWebsocket = ()=>{
  Promise.resolve().then(()=>{
    socket.init()
  }).then(()=>{
    console.log(route.query)
    console.log( user.id)
    console.log( fid)
    if(route.query.type == 1){
      uid.value =  user.id   //  localStorage.getItem("im-userid")
      tid.value =  fid       //   route.query.from
    } else if( route.query.type == 2){
      uid.value = fid
      tid.value = user.id
      isaccept.value = true
    }
    socket.send({uid:  user.id, type: 1})
  }).then(() =>{
    // 主动发送一个请求视频通话消息
    if (route.query.type == 1){
      socket.send({uid:uid.value,to:tid.value,type:3})
    }
  })
}

const accept = () =>{
  socket.send({uid:uid.value,to:tid.value,type:4})
}

// -----------------------------------------------------
const web = websocketStore() // 两个电脑要写https
const v1 = ref();  // 自己的流
const v2 = ref();  // 对方的流
const pc = ref(null);  // 供webrtc接口使用
const mystrea = ref();  // 给对方传数据

web.$subscribe((mutations, state) => {
  console.log(state.msg) // {"from":"3","type":4,"uuid":"e0fea3f2-68f2-4c82-bd9b-837e538a90e6"}
  let msg = JSON.parse(state.msg);
  switch (msg.type) {
    case 4: // 同意了
      sxt().then(res=>{
        // 当前摄像头已经转备好 传递offer信息
        socket.send({uid:uid.value,to:tid.value,type:5})
      })
      break;
    case 5:
      sxt().then(res=>{
        if (pc.value == null){
          createPeerConnection();
        }
        pc.value.createOffer(createOfferAndSendMessage,handleCreateOfferError)
      })
      break;
    case 6:
      if (pc.value == null) {
        createPeerConnection()
      }
      console.log(" type 6 ")
      console.log(msg.message)
      pc.value.setRemoteDescription(new RTCSessionDescription(msg.message));
      doAnswer()
      break;
    case 7:
      pc.value.setRemoteDescription(new RTCSessionDescription(msg.message));
      break;
    case 8:
      console.log(" type 8 ")
      var candidate = new RTCIceCandidate({
        sdpMLineIndex: msg.message.sdpMLineIndex,
        candidate: msg.message.candidate
      });
      pc.value.addIceCandidate(candidate)

      break;
  }
});

// 失败 Offer
const handleCreateOfferError = ()=>{
  console.log(" aaa: handle CreateOffer Error ")
}

// 成功 Offer
const createOfferAndSendMessage = (sessionDescription)=>{
  pc.value.setLocalDescription(sessionDescription)
  socket.send({uid:uid.value,to:tid.value,type:6,message:sessionDescription})
}

//  Answer
const doAnswer = ()=>{
  if (pc.value == null) {
    createPeerConnection()
  }
  pc.value.createAnswer().then(createAnswerAndSendMessage, handleCreateAnswerError);
}

// 失败 Answer
const handleCreateAnswerError = ()=>{
  console.log(" bbb: handle CreateAnswer Error ")
}

// 成功 Answer
const createAnswerAndSendMessage = (sessionDescription)=>{
  pc.value.setLocalDescription(sessionDescription)
  socket.send({uid:uid.value,to:tid.value,type:7,message:sessionDescription})
  // ws.value.send(JSON.stringify({type:"4",uid:uid.value,to:rid.value,message:sessionDescription}))
}

// webrtc接口
const createPeerConnection = ()=>{
  pc.value = new RTCPeerConnection(null); // 外网写服务器
  pc.value.onicecandidate = handleIceCandidate;
  pc.value.onaddstream = handleRemoteStreamAdded;
  for (const trac of mystrea.value.getTracks()){
    pc.value.addTrack(trac,mystrea.value);
  }
}

//  v2 加入
const handleRemoteStreamAdded = (event)=>{
  console.log("v2 ")
  console.log(event)
  v2.value.srcObject = event.stream;
}

//  Candidate
const handleIceCandidate = (event)=>{
  if (event.candidate){
    socket.send({uid:uid.value,to:tid.value,type:8,message:event.candidate})
  }
}

//开启摄像头
const sxt = ()=>{
  return new Promise((resolve,reject)=>{
    // cs 中调摄像头
    navigator.mediaDevices.getUserMedia({
      audio: true,
      video: true,
    }).then(function (value) {
      mystrea.value = value
      v1.value.srcObject = value
    }).then(()=>resolve())
        .catch(()=>reject());
  })
}


</script>

<style>

</style>